package com.sddnytsh.body_buildingsystem.components

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.Send
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.sddnytsh.body_buildingsystem.data.state.UserState
import com.sddnytsh.body_buildingsystem.components.SimpleAvatarImage
import com.sddnytsh.body_buildingsystem.components.DefaultAvatar
import com.sddnytsh.body_buildingsystem.network.CommunityApiService
import com.sddnytsh.body_buildingsystem.topic.Comment
import com.sddnytsh.body_buildingsystem.topic.CommunityPost
import com.sddnytsh.body_buildingsystem.utils.DateUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

@Composable
fun CommentReplyWindow(
    comment: Comment,
    post: CommunityPost,
    isVisible: Boolean,
    onDismiss: () -> Unit,
    coroutineScope: CoroutineScope,
    communityApiService: CommunityApiService,
    onReplyAdded: () -> Unit
) {
    if (isVisible) {
        Dialog(
            onDismissRequest = onDismiss,
            properties = DialogProperties(
                dismissOnBackPress = true,
                dismissOnClickOutside = true
            )
        ) {
            ReplyWindowContent(
                comment = comment,
                post = post,
                onDismiss = onDismiss,
                coroutineScope = coroutineScope,
                communityApiService = communityApiService,
                onReplyAdded = onReplyAdded
            )
        }
    }
}

@Composable
private fun ReplyWindowContent(
    comment: Comment,
    post: CommunityPost,
    onDismiss: () -> Unit,
    coroutineScope: CoroutineScope,
    communityApiService: CommunityApiService,
    onReplyAdded: () -> Unit
) {
    var replies by remember { mutableStateOf<List<Comment>>(emptyList()) }
    var isLoadingReplies by remember { mutableStateOf(false) }
    var replyText by remember { mutableStateOf("@${comment.author ?: "用户${comment.userId}"} ") }
    var isSubmittingReply by remember { mutableStateOf(false) }

    // 加载回复
    LaunchedEffect(comment.id) {
        isLoadingReplies = true
        try {
            val result = communityApiService.getReplies(comment.id, 1, 50)
            result.onSuccess { data ->
                val replyList = data["replies"] as? List<Map<String, Any>> ?: emptyList()
                replies = replyList.map { replyData ->
                    Comment(
                        id = (replyData["id"] as? Number)?.toLong() ?: 0L,
                        postId = (replyData["postId"] as? Number)?.toLong() ?: 0L,
                        userId = (replyData["userId"] as? Number)?.toLong() ?: 0L,
                        content = replyData["content"] as? String ?: "",
                        likeCount = (replyData["likeCount"] as? Number)?.toInt() ?: 0,
                        isLiked = replyData["isLiked"] as? Boolean ?: false,
                        createdAt = replyData["createdAt"] as? String ?: "",
                        author = replyData["author"] as? String,
                        parentId = (replyData["parentId"] as? Number)?.toLong(),
                        rootId = (replyData["rootId"] as? Number)?.toLong(),
                        isDeleted = replyData["isDeleted"] as? Boolean ?: false
                    )
                }
            }
        } catch (e: Exception) {
            // 处理错误
        } finally {
            isLoadingReplies = false
        }
    }

    Card(
        modifier = Modifier
            .fillMaxWidth()
            .fillMaxHeight(0.8f)
            .padding(16.dp),
        shape = RoundedCornerShape(16.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
    ) {
        Column(
            modifier = Modifier.fillMaxSize()
        ) {
            // 标题栏
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "回复 ${comment.author ?: "用户${comment.userId}"}",
                    style = MaterialTheme.typography.titleMedium.copy(
                        fontWeight = FontWeight.Bold
                    )
                )
                
                TextButton(onClick = onDismiss) {
                    Text("关闭", color = Color(0xFF666666))
                }
            }

            Divider()

            // 回复列表
            Box(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxWidth()
            ) {
                if (isLoadingReplies) {
                    Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator()
                    }
                } else if (replies.isEmpty()) {
                    Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = "暂无回复",
                            color = Color.Gray,
                            style = MaterialTheme.typography.bodyMedium
                        )
                    }
                } else {
                    LazyColumn(
                        modifier = Modifier.fillMaxSize(),
                        contentPadding = PaddingValues(16.dp),
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        items(replies) { reply ->
                            ReplyWindowItem(
                                reply = reply,
                                onReplyLikeUpdate = { replyId: Long, isLiked: Boolean, likeCount: Int ->
                                    // 更新回复的点赞状态
                                    replies = replies.map { r ->
                                        if (r.id == replyId) {
                                            r.copy(isLiked = isLiked, likeCount = likeCount)
                                        } else {
                                            r
                                        }
                                    }
                                }
                            )
                        }
                    }
                }
            }

            Divider()

            // 回复输入区域
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                verticalAlignment = Alignment.Bottom
            ) {
                OutlinedTextField(
                    value = replyText,
                    onValueChange = { replyText = it },
                    placeholder = { Text("输入回复内容...") },
                    modifier = Modifier.weight(1f),
                    maxLines = 3,
                    colors = OutlinedTextFieldDefaults.colors(
                        focusedBorderColor = Color(0xFF4361EE),
                        unfocusedBorderColor = Color(0xFFE0E0E0)
                    )
                )
                
                Spacer(modifier = Modifier.width(8.dp))
                
                IconButton(
                    onClick = {
                        if (replyText.trim().isNotEmpty() && !isSubmittingReply) {
                            coroutineScope.launch {
                                isSubmittingReply = true
                                try {
                                    val currentUserId = UserState.currentUserId
                                    if (currentUserId != null) {
                                        val result = communityApiService.createReply(
                                            postId = post.id,
                                            parentId = comment.id,
                                            rootId = comment.id,
                                            content = replyText.trim()
                                        )
                                        result.onSuccess { newReply ->
                                            // 立即将新回复添加到列表中
                                            val newReplyComment = Comment(
                                                id = newReply.id,
                                                postId = newReply.postId,
                                                userId = newReply.userId,
                                                content = newReply.content,
                                                likeCount = newReply.likeCount,
                                                isLiked = newReply.isLiked,
                                                createdAt = newReply.createdAt,
                                                author = newReply.author,
                                                parentId = newReply.parentId,
                                                rootId = newReply.rootId,
                                                isDeleted = newReply.isDeleted
                                            )
                                            
                                            // 将新回复添加到列表开头
                                            replies = listOf(newReplyComment) + replies
                                            
                                            // 清空输入框
                                            replyText = ""
                                            
                                            // 通知父组件刷新
                                            onReplyAdded()
                                        }
                                    }
                                } catch (e: Exception) {
                                    // 处理错误
                                } finally {
                                    isSubmittingReply = false
                                }
                            }
                        }
                    },
                    enabled = replyText.trim().isNotEmpty() && !isSubmittingReply
                ) {
                    if (isSubmittingReply) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(20.dp),
                            strokeWidth = 2.dp
                        )
                    } else {
                        Icon(
                            imageVector = Icons.Filled.Send,
                            contentDescription = "发送",
                            tint = Color(0xFF4361EE)
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun ReplyWindowItem(
    reply: Comment,
    onReplyLikeUpdate: (Long, Boolean, Int) -> Unit
) {
    var isLiked by remember { mutableStateOf(reply.isLiked) }
    var likeCount by remember { mutableStateOf(reply.likeCount) }
    val coroutineScope = rememberCoroutineScope()
    val communityApiService = remember { CommunityApiService() }

    Row(
        modifier = Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.Top
    ) {
        // 用户头像
        if (reply.authorAvatar != null) {
            SimpleAvatarImage(
                avatarUrl = reply.authorAvatar,
                fallbackName = reply.author ?: "用户",
                size = 32.dp
            )
        } else {
            DefaultAvatar(
                name = reply.author ?: "用户",
                size = 32.dp
            )
        }

        Spacer(modifier = Modifier.width(12.dp))

        // 回复内容
        Column(
            modifier = Modifier.weight(1f)
        ) {
            // 用户名和时间
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = reply.author ?: "用户${reply.userId}",
                    style = MaterialTheme.typography.bodyMedium.copy(
                        fontWeight = FontWeight.Medium,
                        color = Color(0xFF333333)
                    )
                )
                
                Spacer(modifier = Modifier.width(8.dp))
                
                Text(
                    text = DateUtils.formatDate(reply.createdAt),
                    style = MaterialTheme.typography.bodySmall.copy(
                        color = Color(0xFF999999)
                    )
                )
            }

            Spacer(modifier = Modifier.height(4.dp))

            // 回复内容
            Text(
                text = reply.content,
                style = MaterialTheme.typography.bodyMedium.copy(
                    color = Color(0xFF333333)
                ),
                modifier = Modifier.fillMaxWidth()
            )

            Spacer(modifier = Modifier.height(8.dp))

            // 点赞按钮
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.clickable {
                    val currentUserId = UserState.currentUserId
                    if (currentUserId != null) {
                        coroutineScope.launch {
                            try {
                                val result = communityApiService.toggleCommentLike(currentUserId, reply.id)
                                if (result.isSuccess) {
                                    isLiked = !isLiked
                                    likeCount = if (isLiked) likeCount + 1 else likeCount - 1
                                    onReplyLikeUpdate(reply.id, isLiked, likeCount)
                                }
                            } catch (e: Exception) {
                                // 处理错误
                            }
                        }
                    }
                }
            ) {
                Icon(
                    imageVector = if (isLiked) Icons.Filled.Favorite else Icons.Filled.FavoriteBorder,
                    contentDescription = "点赞",
                    tint = if (isLiked) Color(0xFFE91E63) else Color(0xFF999999),
                    modifier = Modifier.size(16.dp)
                )
                
                Spacer(modifier = Modifier.width(4.dp))
                
                Text(
                    text = likeCount.toString(),
                    style = MaterialTheme.typography.bodySmall.copy(
                        color = if (isLiked) Color(0xFFE91E63) else Color(0xFF999999)
                    )
                )
            }
        }
    }
}
